package br.com.appwebpizzaria.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.appwebpizzaria.modelo.CarrinhoDeCompras;

/**
 * Servlet implementation class CarrinhoDeComprasAction
 */
@WebServlet("/CarrinhoDeComprasAction")
public class CarrinhoDeComprasAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processaRequisicao(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		processaRequisicao(request, response);
		
	}
	
	private void processaRequisicao(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		
		HttpSession session = request.getSession();
		
		CarrinhoDeCompras carrinho = (CarrinhoDeCompras) session.getAttribute("carrinho");		
		if("".equals(carrinho) || carrinho == null){			
			carrinho = new CarrinhoDeCompras();
		}
		
		String cmd = request.getParameter("cmd");
		
		if("AdicionarItem".equals(cmd)){
			long codigo = Long.parseLong(request.getParameter("codigo"));
			carrinho.adicionarItem(codigo);
			session.setAttribute("carrinho", carrinho);
			RequestDispatcher view = request.getRequestDispatcher("mostrarCarrinho.jsp");
			view.forward(request, response);
			
		}else if ("ExcluirItem".equals(cmd)) {
			long codigo = Long.parseLong(request.getParameter("codigo"));
			carrinho.removerItem(codigo);
			session.setAttribute("carrinho", carrinho);
			RequestDispatcher view = request.getRequestDispatcher("mostrarCarrinho.jsp");
			view.forward(request, response);
			
		}else if ("FecharPedido".equals(cmd)) {
			RequestDispatcher view = request.getRequestDispatcher("meuPedido.jsp");
			view.forward(request, response);
		}
		
	}
}
